#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <clib_sock.h>
#include "HttpDefine.h"
#include "HttpProtocolParse.h"


using namespace std;
using namespace HttpFrame;

int main(int argc,char *argv[])
{

    if(argc <=2)
    {
        cerr << "usage:ip port"<<endl;
        return -1;
    }

    
    char szSendBuffer[1024*10]={0};
    char szRecvBuffer[1024*10]={0};

    while(1)
    {
        memset(szSendBuffer,0,sizeof(szSendBuffer));
        memset(szRecvBuffer,0,sizeof(szRecvBuffer));

        std::string strLine;
        
        if(getline(cin,strLine))
        {
            CmdEchoRequest req;
            memset(&req,0,sizeof(req));
            snprintf(req.szData,sizeof(req.szData)-1,"%s",strLine.c_str());

            Hton(&req);

            CStreamHttpProtocolParse reqParse(szSendBuffer,sizeof(szSendBuffer));

            cout <<"client_name="<<reqParse.ClientName()<<endl;
            
            reqParse.AddExtPara("X_ABSTRATCE", strLine.c_str());
            
            if(reqParse.MakeRequest(10,HF_CMD_TYPE_ECHO
		                                  ,&req,sizeof(CmdEchoRequest)))
            {
                return 0;
            }

            int nRet = 0;
            int nLen = 0;
             
            cout << "send packet:"<<(char*)reqParse.GetData()<<endl;

            clib_sock sock(argv[1],atoi(argv[2]));
 
            sock.set_cluster(17544);
        
            nRet = sock.connect();
        
            if(nRet)
            {
                cout << "connet to "<<argv[1]<<":"<<argv[2]<<" false!"<<endl;
                sock.close();
                return -1;
            }

            while(nLen < (int)reqParse.GetPackLen())
            {
                nRet = sock.send(szSendBuffer+nLen, reqParse.GetPackLen()-nLen, 1);
                cout << "send ret="<<nRet << endl;
                if(nRet <0)
                {
                    cout << "send pack error!nPackLen="<<reqParse.GetPackLen()<<",nLen="<<nLen <<",nRet="<<nRet<<endl;
                    sock.close();
                    return -1;
                }
                nLen += nRet;
            }

             nRet = 0;
             nLen = 0;

             while(CHttpProtocolParse::IsPackOk(szRecvBuffer,nLen)!=true)
             {
                  nRet = sock.recv(szRecvBuffer+nLen, sizeof(szRecvBuffer)-nLen-1, 1);
                  cout << "recv ret="<<nRet << endl;
                  if(nRet <= 0)
                  {
                      cout << "recv pack error!nLen="<<nLen <<",nRet="<<nRet<<endl;
                      sock.close();
                      return -1;
                  }
                  nLen += nRet;
             }

           cout << "recv packet:"<< szRecvBuffer << endl;
           sock.close();
            
        }
        
    }
    return 0;
}

